//
//  DYRiqiChoiceView.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/3/10.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import SwiftDate

class DYRiqiChoiceView: SYBaseView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var compClosure:((String,String,String,String,String)->Void)?
    var startDateParam: String?
    var endDateParam: String?
    
    var collectionView: UICollectionView!
    var titles: [String] = ["今天", "明天"]
    var tips: [String] = ["", ""]
    var riqis: [String] = []
    var times:[String] = []
    var selectTime: String? {
        didSet {
            showLb.text = "已选：\(selectRiqi ?? "") \(selectTime ?? "")"
            compAction()
        }
    }
    var selectRiqi: String? {
        didSet {
            showLb.text = "已选：\(selectRiqi ?? "") \(selectTime ?? "")"
            compAction()
        }
    }
    var jishu: Int = 100
    var dengfen: Int = 10  {
        didSet {
            zongshu = jishu * (dengfen - 1)
        }
    }
    var zongshu : Int = 900
    var lastLow: Double = 0.0
    var lastHigh: Double = 1.0
    
    var selectIndex: Int = 0
    
    var bgView: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor.white
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        return v
    }()
    
    var bgBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        return v
    }()
    
    var compBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = Constant.blueColor
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        v.setTitle("完成", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 18.autoBoldFontSize()
        return v
    }()
    
    
    var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 17.autoBoldFontSize()
        v.textColor = UIColor(hex: 0x1B1B1B)
        v.text = "选择查询时间"
        return v
    }()
    
    var showLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 14.autoFontSize()
        v.textColor = UIColor(hex: 0xFF5502)
        v.backgroundColor = UIColor(hex: 0xFFEEE5)
        v.textAlignment = .center
        return v
    }()
    
    var lowTimeLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 11.autoFontSize()
        v.textColor = UIColor(hex: 0x333333)
        
        return v
    }()
    
    var highTimeLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 11.autoFontSize()
        v.textColor = UIColor(hex: 0x333333)
        
        return v
    }()
    
    var rangeSlider:SYRangeSlider = {
        let v = SYRangeSlider()
        v.addTarget(self, action: #selector(rangeSliderValueChanged), for: .touchUpInside)
        v.trackHighlightTintColor = Constant.blueColor!
        v.trackTintColor = Constant.bgViewColor!
        v.trackHeight = 2
        v.lowerValue = 0.0
        v.upperValue = 1.0
        return v
    }()
    
    func configure(_ models: [DYMSTimeChoiceModel]) {
        times = models.map {
            let s = ($0.strK ?? "").components(separatedBy: ":")
            return "\(s.first ?? ""):\(s[1])"
        }
        
        lowTimeLb.text = times.first
        
        if times.last == "00:00" {
            highTimeLb.text = "24:00"
            times[models.count - 1] = "24:00"
        } else {
            highTimeLb.text = times.last
        }
        dengfen = models.count
        selectTime = "\(times.first ?? "")-\(highTimeLb.text ?? "")"
    }
    
    func compAction() {
        let fs = self.selectRiqi?.components(separatedBy: "月")
        let es = fs?.last?.components(separatedBy: "日")
        let ts = self.selectTime?.components(separatedBy: "-")
        let dateStr = "\(Date().year)-\(fs?.first ?? "")-\(es?.first ?? "")"
        startDateParam = "\(dateStr) \(ts?.first ?? "")\(ts?.first ?? ""):00"
        endDateParam = "\(dateStr) \(ts?.last ?? "")\(ts?.last ?? ""):00"
        compClosure?(startDateParam ?? "", endDateParam ?? "", selectRiqi ?? "", "", selectTime ?? "")
    }
    
    override func initViews() {
        self.isHidden = true
        self.backgroundColor = .clear
        
        for i in 0..<14 {
            
            let riqi = Date() + i.days
            let riqiStr = riqi.sy_toString(format: "MM月dd日")
            riqis.append(riqiStr)
            
            if i > 1 {
                var tipStr = riqi.sy_toString(format: "MM.dd")
                if tipStr.first == "0" {
                    tipStr.removeFirst()
                }
                
                tips.append(getWeekStr(index: riqi.weekday))
                titles.append(tipStr)
            }
        }
        selectRiqi = riqis.first
        
        bgBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
            }
        }
        compBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
            }
        }
        
        addSubview(bgBt)
        addSubview(bgView)
        bgView.addSubview(titleLb)
        bgView.addSubview(showLb)
        bgView.addSubview(rangeSlider)
        bgView.addSubview(lowTimeLb)
        bgView.addSubview(highTimeLb)
        addSubview(compBt)
        setCollectionView()
        
        rangeSlider.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(137.0.autoWidth())
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(20.autoWidth())
        }
        lowTimeLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(122.0.autoWidth())
            make.left.equalToSuperview().offset(15.autoWidth())
            make.height.equalTo(10.autoWidth())
        }
        highTimeLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(122.0.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(10.autoWidth())
        }
        bgView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(10.autoWidth())
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(300.autoWidth() + BOTTOM_SAFE_HEIGHT)
        }
        bgBt.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        titleLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20.autoWidth())
            make.centerX.equalToSuperview()
            make.height.equalTo(17.autoWidth())
        }
        showLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(172.autoWidth())
            make.left.right.equalToSuperview()
            make.height.equalTo(40.autoWidth())
        }
        compBt.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10.autoWidth() - BOTTOM_SAFE_HEIGHT)
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(44.autoWidth())
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(65.autoWidth())
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(42.autoWidth())
        }
    }

    func setCollectionView() {
            
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 83, height: 40)
//        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        layout.scrollDirection = .horizontal
        
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DYRiqiChoiceCell.self, forCellWithReuseIdentifier: NSStringFromClass(DYRiqiChoiceCell.self))
        
        self.bgView.addSubview(self.collectionView)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return titles.count//14
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
            let cell: DYRiqiChoiceCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYRiqiChoiceCell.self), for: indexPath) as? DYRiqiChoiceCell
            if let d = titles.objectAtIndex(index: indexPath.row) {
                if selectIndex == indexPath.row {
                    cell?.configCell(d, tips[indexPath.row], true)
                } else {
                    cell?.configCell(d, tips[indexPath.row], false)
                }
            }
            return cell!
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectIndex = indexPath.row
        selectRiqi = riqis[indexPath.row]
        self.collectionView.reloadData()
    }
    
    @objc func rangeSliderValueChanged(sender: SYRangeSlider) {
        
        print("rangeSliderValueChanged.value ====== \(sender.lowerValue),\(sender.upperValue)")
        
        let lowInt: Int = Int(sender.lowerValue * Double(zongshu) / Double(jishu))
        var low: Int = 0
        
        let highInt: Int = Int(sender.upperValue * Double(zongshu) / Double(jishu))
        var high: Int = 0
        
        if lastLow != sender.lowerValue {
            
            if lastLow < sender.lowerValue {// 当low往右滑动时 加1格
                
                // 防止low和hight相等
                if sender.upperValue - sender.lowerValue > 1.0/Double(dengfen) {
                    low = lowInt*jishu + jishu
                    rangeSlider.lowerValue = Double(low)/Double(zongshu)
                    
                } else {
                    low = lowInt*jishu
                    rangeSlider.lowerValue = Double(low)/Double(zongshu)
                }
                    
            } else {// 当low往左滑动时 减1格
                low = lowInt*jishu
                rangeSlider.lowerValue = Double(low)/Double(zongshu)
            }
            
            lastLow = rangeSlider.lowerValue
        } else {
            low = lowInt*jishu
        }
        
        if lastHigh != sender.upperValue {

            if lastHigh < sender.upperValue {// 当high往右滑动时 加1格
                high = highInt*jishu + jishu
                print("highInt1", highInt)
                rangeSlider.upperValue = Double(high)/Double(zongshu)
            } else {// 当high往左滑动时 减1格
                
                // 防止low和hight相等
                if sender.upperValue - sender.lowerValue > 1.0/Double(dengfen) {
                    high = highInt*jishu
                    print("highInt2", highInt)
                    rangeSlider.upperValue = Double(high)/Double(zongshu)
                } else {
                    high = highInt*jishu + jishu
                    print("highInt3", highInt)
                    rangeSlider.upperValue = Double(high)/Double(zongshu)
                }
            }
            
            lastHigh = rangeSlider.upperValue
        } else {
            high = highInt*jishu
            print("highInt4", highInt)
        }
        
        
        selectTime = "\(getTime(index: low/jishu))-\(getTime(index: high/jishu))"
        
        print("rangeSliderValueChanged.value ++++ \(rangeSlider.lowerValue),\(rangeSlider.upperValue)")
    }
    
    func getTime(index: Int) -> String {
        if index >= times.count {
            return times.last ?? ""
        }
        return times[index]
    }
}


class DYRiqiChoiceCell: UICollectionViewCell {
    
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 13.autoFontSize()
        
        return v
    }()
    
    fileprivate var tipLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 10.autoFontSize()
        
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ title: String, _ tip: String, _ isSelect: Bool? = false) {

        let hasTip = !tip.isEmpty
        titleLb.text = title
        tipLb.text = tip
        if isSelect == true {
            self.backgroundColor = Constant.blueColor
            titleLb.textColor = .white
            tipLb.textColor = .white
        } else {
            self.backgroundColor = .white
            self.layer.borderWidth = 0.5
            self.layer.borderColor = Constant.blueColor?.cgColor
            titleLb.textColor = UIColor(hex: 0x3E3E3E)
            tipLb.textColor = UIColor(hex: 0x666666)
        }
        if hasTip {
            titleLb.snp.remakeConstraints { (make) in
                
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview().offset(6.autoWidth())
                make.height.equalTo(13.0.autoWidth())
            }
            tipLb.snp.remakeConstraints { (make) in
                
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview().offset(-6.autoWidth())
                make.height.equalTo(13.0.autoWidth())
            }
        } else {
            titleLb.snp.remakeConstraints { (make) in
                
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
                make.height.equalTo(13.0.autoWidth())
            }
            tipLb.snp.remakeConstraints { (make) in
                
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
                make.height.equalTo(13.0.autoWidth())
            }
        }
    }
    
    fileprivate func initViews() {
        
        self.layer.cornerRadius = 4.autoWidth()
        self.layer.masksToBounds = true
        addSubview(titleLb)
        addSubview(tipLb)
        titleLb.snp.makeConstraints { (make) in
            
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(13.0.autoWidth())
        }
        tipLb.snp.makeConstraints { (make) in
            
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(13.0.autoWidth())
        }
    }
}
